import re

from lxml import etree

from PageObjectRequests import base_url
from util import http_utils
from util.selenium.webdriver.common.by import By

from base.BaseMethod import BM
from util.DataQuery.FormDataDecorator import FormDataDecorator
from util.g import g


class WriteRdcostForm():
    form_btn_loc = (By.LINK_TEXT, '企业年度研究开发费用结构明细表')
    content_iframe_loc = (By.CSS_SELECTOR, "#innocomFrame")

    def __init__(self, driver=None):
        self.driver = driver
        self.flag = False
        self.record_var = "{}Record".format(self.class_name)
        setattr(g, self.record_var, list())

    @property
    def class_name(self):
        return self.__class__.__name__

    @FormDataDecorator
    def main(self, rd_id='', peryear='', int_amount='', int_labor='', int_direct_inv='', int_de_lta='', int_aia='', int_design='', int_ecct='', int_other='',ext_amount='', ext_inchina='',amount='', reporter='', sig_date='', sort_num=''):
        try:
            li_list = getattr(g, self.record_var)
            if not self.flag:
                # BM.click(driver=self.driver, ele_loc=self.form_btn_loc)
                ele = BM.get_ele(driver=self.driver, ele_loc=self.form_btn_loc, time=6)
                detail_url = ele.get_attribute("href")
                if not g.all_optimized:
                    BM.switch_to_frame(driver=self.driver, ele_loc=self.content_iframe_loc)
                BM.get_cookie(driver=self.driver)
                detail_url = detail_url if detail_url.startswith("https://") else \
                    base_url + (detail_url if detail_url.startswith("/") else "/" + detail_url)
            if not self.flag:

                page_res = http_utils.send_get(detail_url, driver=self.driver)
                page_text = page_res.get("text")
                page_tree = etree.HTML(page_text)
                lis = page_tree.xpath("//ul[@id='attendance']/li/a")
                self.flag = True
                for li in lis:
                    href = li.attrib.get("href")
                    full_url = href if href.startswith("https://") else \
                        base_url + (href if href.startswith("/") else "/" + href)
                    param_str = full_url[full_url.index("?") + 1:]
                    param_dict = {p.split("=")[0]: p.split("=")[1] for p in param_str.split("&")}
                    year = param_dict.get("year")
                    res = None
                    while True:
                        if not res:
                            res = http_utils.send_get(full_url, driver=self.driver)
                        text = res.get("text")
                        # 替换掉国网随机插入的字符串
                        random_insert_chars_p = ".*?([\r\n].[0-9a-zA-Z]{4,}[\r\n].).*?"
                        res = re.findall(random_insert_chars_p, text, re.S)
                        for i in res:
                            text = text.replace(i, "")
                        tree = etree.HTML(text)
                        tr_list = tree.xpath(
                            "//form[@id='DataEprRdFee_list']//div[@class='tableRegionDivBody']//tbody/tr")
                        for tr in tr_list:
                            rd_id_str = BM.get_first(tr.xpath("./td[2]/text()"))
                            sign_str = "{}:{}".format(year, rd_id_str)
                            li_list.append(sign_str)

                        # 匹配下一页 url
                        next_list = tree.xpath("//form[@id='DataEprRdFee_list']//div[@class='page']/ul/li[4]/a")
                        next_a = BM.get_first(next_list)
                        next_onclick = None if not next_a else next_a.attrib.get("onclick")
                        if not next_onclick:
                            break
                        else:
                            # 获取下一页url
                            next_url_pattern = """.*?setAttribute\(['|"]action['|"],'(.*?)'.*?"""
                            next_res = re.findall(next_url_pattern, next_onclick, re.S)
                            next_url = BM.get_first(next_res)
                            next_page_pattern = """.*?value=['|"](\d+)['|"];.*?"""
                            next_page_res = re.findall(next_page_pattern, next_onclick, re.S)
                            next_page = BM.get_first(next_page_res)
                            if not next_url or not next_page:
                                break
                            next_url = (base_url + next_url) if not next_url.startswith("https://") else next_url
                            query_data = {
                                "ec_i": "",
                                "DataEprRdFee_list_crd": "10",
                                "DataEprRdFee_list_p": next_page,
                                "DataEprRdFee_list_a_dataEprRdFee_pxmbh": "",
                                "DataEprRdFee_list_a_dataEprRdFee_pnbyjtrhj": "",
                                "DataEprRdFee_list_a_dataEprRdFee_pryrghj": "",
                                "DataEprRdFee_list_a_dataEprRdFee_pzjtrhj": "",
                                "DataEprRdFee_list_a_dataEprRdFee_pzjftxhj": "",
                                "DataEprRdFee_list_a_dataEprRdFee_pwxzchj": "",
                                "DataEprRdFee_list_a_dataEprRdFee_psjfhj": "",
                                "DataEprRdFee_list_a_dataEprRdFee_psbtsfhj": "",
                                "DataEprRdFee_list_a_dataEprRdFee_pqtfyhj": "",
                                "DataEprRdFee_list_a_dataEprRdFee_pwtwbtrhj": "",
                                "DataEprRdFee_list_a_dataEprRdFee_pjnwbtrhj": "",
                                "DataEprRdFee_list_a_dataEprRdFee_pyjkfnwhj": "",
                                "DataEprRdFee_list_a_dataEprRdFee_pqytbr": "",
                                "DataEprRdFee_list_rd": "10"
                            }
                            tree = etree.HTML(text)
                            query_data["ec_i"] = BM.get_first(tree.xpath("//input[@name='ec_i']/@value"))
                            query_data["DataEprRdFee_list_a_dataEprRdFee_pxmbh"] = BM.get_first(tree.xpath(
                                "//input[@name='DataEprRdFee_list_a_dataEprRdFee_pxmbh']/@value"))
                            query_data["DataEprRdFee_list_a_dataEprRdFee_pnbyjtrhj"] = BM.get_first(tree.xpath(
                                "//input[@name='DataEprRdFee_list_a_dataEprRdFee_pnbyjtrhj']/@value"))
                            query_data["DataEprRdFee_list_a_dataEprRdFee_pryrghj"] = BM.get_first(tree.xpath(
                                "//input[@name='DataEprRdFee_list_a_dataEprRdFee_pryrghj']/@value"))
                            query_data["DataEprRdFee_list_a_dataEprRdFee_pzjtrhj"] = BM.get_first(tree.xpath(
                                "//input[@name='DataEprRdFee_list_a_dataEprRdFee_pzjtrhj']/@value"))
                            query_data["DataEprRdFee_list_a_dataEprRdFee_pzjftxhj"] = BM.get_first(tree.xpath(
                                "//input[@name='DataEprRdFee_list_a_dataEprRdFee_pzjftxhj']/@value"))
                            query_data["DataEprRdFee_list_a_dataEprRdFee_pwxzchj"] = BM.get_first(tree.xpath(
                                "//input[@name='DataEprRdFee_list_a_dataEprRdFee_pwxzchj']/@value"))
                            query_data["DataEprRdFee_list_a_dataEprRdFee_psjfhj"] = BM.get_first(tree.xpath(
                                "//input[@name='DataEprRdFee_list_a_dataEprRdFee_psjfhj']/@value"))
                            query_data["DataEprRdFee_list_a_dataEprRdFee_psbtsfhj"] = BM.get_first(tree.xpath(
                                "//input[@name='DataEprRdFee_list_a_dataEprRdFee_psbtsfhj']/@value"))
                            query_data["DataEprRdFee_list_a_dataEprRdFee_pqtfyhj"] = BM.get_first(tree.xpath(
                                "//input[@name='DataEprRdFee_list_a_dataEprRdFee_pqtfyhj']/@value"))
                            query_data["DataEprRdFee_list_a_dataEprRdFee_pwtwbtrhj"] = BM.get_first(tree.xpath(
                                "//input[@name='DataEprRdFee_list_a_dataEprRdFee_pwtwbtrhj']/@value"))
                            query_data["DataEprRdFee_list_a_dataEprRdFee_pjnwbtrhj"] = BM.get_first(tree.xpath(
                                "//input[@name='DataEprRdFee_list_a_dataEprRdFee_pjnwbtrhj']/@value"))
                            query_data["DataEprRdFee_list_a_dataEprRdFee_pyjkfnwhj"] = BM.get_first(tree.xpath(
                                "//input[@name='DataEprRdFee_list_a_dataEprRdFee_pyjkfnwhj']/@value"))
                            query_data["DataEprRdFee_list_a_dataEprRdFee_pqytbr"] = BM.get_first(tree.xpath(
                                "//input[@name='DataEprRdFee_list_a_dataEprRdFee_pqytbr']/@value"))
                            res = http_utils.send_post(next_url, data=query_data, driver=self.driver)

            year_diff_num = g.year - peryear
            pro_num = 'RD' + str(rd_id).zfill(2) if rd_id != 0 else "其他"
            sign = "{}:{}".format(peryear, pro_num)
            if year_diff_num > 3:
                li_list.append(sign)
                return True

            if sign in li_list:
                g.logger.info("（{}） 已存在".format(sign))
                return True
            # # 这里 int_amount, amount 两个参数都不需要填写，系统会自动生成

            add_url = "https://gqqy.chinatorch.org.cn/xonlinereport/inforeport/DataInnocom/addDataEprRdFee.do"
            add_res = http_utils.send_get(url=add_url, params={"year": str(peryear)}, driver=self.driver)
            token = add_res.get("token")
            text = add_res.get("text")

            save_url = "https://gqqy.chinatorch.org.cn/xonlinereport/inforeport/DataInnocom/saveOrUpdateDataEprRdFee.do"
            int_amount = float(int_labor) + float(int_direct_inv) + float(int_de_lta) + float(int_aia) \
                         + float(int_design) + float(int_ecct) + float(int_other)
            data = {
                "dataEprRdFee.id": "",
                "dataInnocom.id": "",
                "dataInnocomId": "",
                "dataId": "",
                "curYear": str(peryear),
                "struts.token.name": "token",
                "token": token,
                "dataEprRdFee.pxmbh": pro_num,
                "dataEprRdFee.pnbyjtrhj": str(int_amount),
                "dataEprRdFee.pryrghj": str(int_labor),
                "dataEprRdFee.pzjtrhj": str(int_direct_inv),
                "dataEprRdFee.pzjftxhj": str(int_de_lta),
                "dataEprRdFee.pwxzchj": str(int_aia),
                "dataEprRdFee.psjfhj": str(int_design),
                "dataEprRdFee.psbtsfhj": str(int_ecct),
                "dataEprRdFee.pqtfyhj": str(int_other),
                "dataEprRdFee.pwtwbtrhj": str(ext_amount),
                "dataEprRdFee.pjnwbtrhj": str(ext_inchina),
                "dataEprRdFee.pyjkfnwhj": str(int_amount + float(ext_amount)),
                "dataEprRdFee.pqytbr": reporter,
                "dataEprRdFee.pqytbrqzrq": sig_date,
                "dataEprRdFee.position": str(sort_num),
            }
            tree = etree.HTML(text)
            data["dataEprRdFee.id"] = BM.get_first(tree.xpath("//input[@name='dataEprRdFee.id']/@value"))
            data["dataInnocom.id"] = BM.get_first(tree.xpath("//input[@name='dataInnocom.id']/@value"))
            data["dataInnocomId"] = BM.get_first(tree.xpath("//input[@name='dataInnocomId']/@value"))
            data["dataId"] = BM.get_first(tree.xpath("//input[@name='dataId']/@value"))

            res = http_utils.send_post(url=save_url, data=data, driver=self.driver)
            text = res.get("text")
            message = res.get("message")
            g.logger.info("企业年度研究开发费用结构明细表（{}）上传结果: {}".format(sign, message))
            if u"成功" in message:
                li_list.append(sign)

        except Exception as err:
            msg = "error: {} file: {} lines: {}".format(
                err, err.__traceback__.tb_frame.f_globals["__file__"],
                err.__traceback__.tb_lineno)
            g.logger.error(msg)
            raise Exception(msg)
